/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: leebean
 * 开发时间: 2019/12/30 20:04
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.operation.common.aop;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.security.CurrentUserContextHolder;
import com.spring.arch.common.security.SecurityLog;
import com.spring.arch.common.security.UserPrincipal;
import com.spring.arch.common.utils.HttpUtils;
import com.spring.arch.uaa.client.AuthClient;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.security.CurrentUserContextHolder;
import com.spring.arch.common.security.SecurityLog;
import com.spring.arch.common.security.UserPrincipal;
import com.spring.arch.common.utils.HttpUtils;
import com.spring.arch.operation.common.enums.Constant;
import com.spring.arch.uaa.client.AuthClient;

import lombok.extern.slf4j.Slf4j;

/**
 * 获取用户凭证Aspect
 *
 * @author leebean
 * @version 1.0.0
 * @since 2019/12/30 20:04
 */
@Aspect
@Slf4j
@Component
public class ServiceAspect {

    @Resource
    private AuthClient authClient;

    @Pointcut("execution(* com.spring.arch..*.controller..*(.., com.spring.arch.common.security.UserPrincipal, ..))")
    public void annotationPointCut() {
    }

    /**
     * 执行方法前的拦截方法
     * @param joinPoint
     * @throws Throwable
     */
    @Around(value = "annotationPointCut()")
    public Object doBeforeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        final String clientIp = HttpUtils.getClientIP(request);
        Signature signature = joinPoint.getSignature();
        log.info("获取用户凭证Aspect请求：[{} <---> {}]", signature.getDeclaringType().getName(), signature.getName());
        UserPrincipal currentUser = CurrentUserContextHolder.getCurrentUser();
        if (currentUser == null) {
            //获取项目id
            final String clientId = request.getHeader(Constant.HEADER_CLIENT_ID);
            if (StringUtils.isBlank(clientId)) {
                SecurityLog.authentication.error("[{}] header param clientId is Empty!!!", clientIp);
                return null;
            }
            ResultDTO<UserPrincipal> dto = authClient.userPrincipal(UUID.fromString(clientId));
            if(dto.isFailure()) {
                SecurityLog.authentication.warn("[{}-{}] request uaa for principal failure", clientIp, clientId);
                return null;
            }
            currentUser = dto.getData();
        }
        Object[] obj = joinPoint.getArgs();
        Class[] parameterTypes = ((MethodSignature) signature).getParameterTypes();
        for(int i = 0; i < parameterTypes.length; i++) {

            if(parameterTypes[i] == UserPrincipal.class) {
                obj[i] = currentUser;
            }
        }
        return joinPoint.proceed(obj);
    }
}
